package com.lazy.utils.interceptor;

import com.lazy.utils.common.FastJsonUtil;
import com.lazy.utils.utils.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Controller层日志拦截器
 *
 * @author zk
 * @version 1.0
 * @date 2018-06-27 16:06
 */
@Slf4j
@Aspect
@Component
public class ControllerCostLogInterceptor {

	/**
	 * Pointcut
	 * 定义Pointcut，Pointcut的名称为aspectjMethod()，此方法没有返回值和参数
	 * 该方法就是一个标识，不进行调用
	 */
	@Pointcut("execution(public * com.lazy.*.controller.*Controller.*(..))")
	private void aspectjMethod() {
	}

	@Around(value = "aspectjMethod()")
	public Object methodLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		Object[] args = proceedingJoinPoint.getArgs();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		Class<?> classTarget = proceedingJoinPoint.getTarget().getClass();
		MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
		Method targetMethod = methodSignature.getMethod();

		long beginTime = System.currentTimeMillis();
		Object result = proceedingJoinPoint.proceed(args);
		long endTime = System.currentTimeMillis();
		long consumeTime = endTime - beginTime;

		StringBuilder logMsg = new StringBuilder("\nController execute report -------- " + LocalDateTimeUtil.getCurYmdHms() + " -------------------------------------");
		logMsg.append("\nURI         : ").append(request.getRequestURI()).append(", Method : ").append(request.getMethod());
		logMsg.append("\nController  : ").append(classTarget).append(", Method : ").append(targetMethod.getName());

		if (request.getMethod().equalsIgnoreCase("GET")) {
			logMsg.append("\nQueryString : ").append(StringUtils.isBlank(request.getQueryString()) ? "" : request.getQueryString());
		} else if (request.getMethod().equalsIgnoreCase("POST")) {
			//从request获取参数，mvc层方法参数需要添加 @RequestParam 注解
			logMsg.append("\nParameter   : ").append(FastJsonUtil.obj2json(request.getParameterMap()));
		}

		logMsg.append("\nResponse    : ").append(FastJsonUtil.obj2json(result));
		logMsg.append("\nCost Time   : ").append(consumeTime).append(" ms");
		logMsg.append("\n--------------------------------------------------------------------------------------------");
		log.info(logMsg.toString());

		return result;
	}

}
